package com.lagou.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class LoginInterceptor implements HandlerInterceptor {
    //缓存session
    private List<String> sessionList = new ArrayList<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if ("/login".equals(requestURI)) {//登录页，直接放行
            return true;
        } else {
            Cookie[] cookies = request.getCookies();
            if (cookies == null || cookies.length == 0) {
                response.sendRedirect("/login");
                return false;
            }
            String sessionId = null;
            for (Cookie cookie : cookies) {
                if ("JSESSIONID".equals(cookie.getName())) {
                    sessionId = cookie.getValue();
                }
            }
            boolean hasLogin = false;
            for (String session : sessionList) {
                if (sessionId.equals(session)) {
                    hasLogin = true;
                }
            }
            if (hasLogin) {//已登陆过，放行
                return true;
            }
            //未登录过，登录
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            if ("suncong".equals(username) && "1".equals(password)) {//登录成功，放行
                sessionList.add(sessionId);
                return true;
            }
            //登录失败，跳转到登录页
            response.sendRedirect("/login");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
